import React, { useEffect, useMemo, useState } from 'react';
import { Card, Space, Button, Table, Form, Input, DatePicker, Select, Tag, message } from 'antd';

const { RangePicker } = DatePicker;

// 本地存储键名
const LS_KEY = 'authority-login-logs';

const STATE_OPTIONS = [
  { label: '成功', value: 0 },
  { label: '失败', value: 1 },
];

function fmtDate(ms) {
  const d = new Date(ms);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

function genInitialLogs() {
  const arr = [];
  const now = Date.now();
  const locales = ['北京', '上海', '深圳', '杭州', '成都'];
  const clients = ['Chrome', 'Firefox', 'Edge', 'Safari'];
  const oses = ['Windows', 'macOS', 'Linux', 'Android', 'iOS'];
  const ips = ['192.168.1.1', '10.0.0.2', '172.16.0.3', '127.0.0.1'];
  for (let i = 1; i <= 50; i += 1) {
    const ms = now - i * 3600 * 1000;
    arr.push({
      id: i,
      userName: `user_${i}`,
      ip: ips[i % ips.length],
      locale: locales[i % locales.length],
      client: clients[i % clients.length],
      os: oses[i % oses.length],
      state: i % 3 === 0 ? 1 : 0,
      info: i % 2 ? '登录成功' : '密码错误',
      createTime: fmtDate(ms),
    });
  }
  return arr;
}

function loadFromLS() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return genInitialLogs();
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : genInitialLogs();
  } catch (e) {
    return genInitialLogs();
  }
}

function saveToLS(list) {
  localStorage.setItem(LS_KEY, JSON.stringify(list));
}

export default function LoginInfo() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState(() => loadFromLS());
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });

  useEffect(() => {
    form.setFieldsValue({ userName: undefined, locale: undefined, state: undefined, dateRange: undefined });
  }, [form]);

  const columns = [
    { title: '用户名', dataIndex: 'userName', key: 'userName', width: 180, align: 'center' },
    { title: 'IP地址', dataIndex: 'ip', key: 'ip', width: 150, align: 'center' },
    { title: '登录地点', dataIndex: 'locale', key: 'locale', width: 140, align: 'center' },
    { title: '浏览器', dataIndex: 'client', key: 'client', width: 140, align: 'center' },
    { title: '系统', dataIndex: 'os', key: 'os', width: 140, align: 'center' },
    { title: '状态', dataIndex: 'state', key: 'state', width: 100, align: 'center', render: (v) => <Tag color={v === 0 ? 'green' : 'red'}>{v === 0 ? '成功' : '失败'}</Tag> },
    { title: '信息', dataIndex: 'info', key: 'info', align: 'center' },
    { title: '时间', dataIndex: 'createTime', key: 'createTime', width: 180, align: 'center' },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys) => setSelectedRowKeys(keys),
  };

  const filteredData = useMemo(() => {
    const { userName, locale, state, dateRange } = form.getFieldsValue();
    let list = [...dataList];
    if (userName) list = list.filter((it) => it.userName.includes(userName));
    if (locale) list = list.filter((it) => it.locale.includes(locale));
    if (typeof state === 'number') list = list.filter((it) => it.state === state);
    if (dateRange && dateRange.length === 2) {
      const [start, end] = dateRange;
      const startMs = start?.valueOf();
      const endMs = end?.valueOf();
      list = list.filter((it) => {
        const ms = new Date(it.createTime.replace(/-/g, '/')).getTime();
        return (!startMs || ms >= startMs) && (!endMs || ms <= endMs);
      });
    }
    return list;
  }, [dataList, form]);

  const onSearch = () => {
    message.success('搜索完成');
    setPagination((p) => ({ ...p, current: 1 }));
  };

  const onReset = () => {
    form.resetFields();
    setPagination((p) => ({ ...p, current: 1 }));
  };

  const onTableChange = (p) => setPagination({ current: p.current, pageSize: p.pageSize });

  return (
    <Card title="登录日志">
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        <Form form={form} layout="inline" onFinish={onSearch}>
          <Form.Item label="用户名" name="userName">
            <Input placeholder="支持模糊匹配" allowClear />
          </Form.Item>
          <Form.Item label="登录地点" name="locale">
            <Input placeholder="支持模糊匹配" allowClear />
          </Form.Item>
          <Form.Item label="状态" name="state">
            <Select style={{ width: 160 }} allowClear options={STATE_OPTIONS} placeholder="全部" />
          </Form.Item>
          <Form.Item label="时间范围" name="dateRange">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">搜索</Button>
              <Button onClick={onReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          rowKey="id"
          columns={columns}
          dataSource={filteredData}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            total: filteredData.length,
            showTotal: (t) => `共 ${t} 条`,
          }}
          onChange={onTableChange}
          scroll={{ x: 1200 }}
        />
      </Space>
    </Card>
  );
}